package org.wisdom.data.jpa.support;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.wisdom.exception.BusinessException;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 多租户数据源
 *
 * @author 张智研
 * @date 2022/05/26 13:49
 **/
@SuppressWarnings("FieldMayBeFinal")
@Component
@Slf4j
public class WisdomMultiTenantDataSourceProvider {

    private static Map<String, DruidDataSource> dataSourceMap = new HashMap<>();

    private WisdomMultiTenantDataSourceProvider() {}

    /**
     * 根据传进来的tenantId决定返回的数据源
     *
     * @author 张智研
     * @date 2022/05/26 21:21
     * @param tenantId
     *            租户id
     * @return javax.sql.DataSource
     */
    public static synchronized DataSource getTenantDataSource(String tenantId) {
        WisdomMultiTenantDataSourceProperties wisdomMultiTenantDataSourceProperties =
            SpringUtil.getBean(WisdomMultiTenantDataSourceProperties.class);
        if (dataSourceMap.containsKey(tenantId)) {
            return dataSourceMap.get(tenantId);
        } else {
            List<Map<String, Object>> datasourceList = wisdomMultiTenantDataSourceProperties.getDatasource();
            for (Map<String, Object> ds : datasourceList) {
                DruidDataSource druidDataSource = new DruidDataSource();
                druidDataSource.setUrl((String)ds.get("url"));
                druidDataSource.setUsername((String)ds.get("username"));
                druidDataSource.setPassword((String)ds.get("password"));
                druidDataSource.setDriverClassName((String)ds.get("driver-class-name"));
                dataSourceMap.put((String)ds.get("tenant-id"), druidDataSource);
            }
            if (dataSourceMap.containsKey(tenantId)) {
                DruidDataSource dataSource = dataSourceMap.get(tenantId);
                log.info("切换到租户{}数据源{}", tenantId, dataSource.getUrl());
                return dataSource;
            } else {
                log.error("租户{}没有数据源", tenantId);
                throw new BusinessException("租户" + tenantId + "不存在数据源！");
            }
        }
    }
}
